#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>

pthread_t pt_id;

void *Send_data(void *arg);
int cfd;
struct sockaddr_in serv;
int ms = 100;

int main(int argc, char const *argv[])
{
	int n ;
	char abuf[1024];
	
	if( argc >1)
	{
		ms = atol(argv[1]);
	}

	//1.创建socket
	cfd = socket(AF_INET,SOCK_DGRAM,0);
	if(cfd<0){
		perror("socket error");
		return -1;
	}

	serv.sin_family = AF_INET;
	serv.sin_port = htons(9999);
	inet_pton(AF_INET,"192.168.2.209",&serv.sin_addr.s_addr);

	pthread_create(&pt_id,NULL,Send_data,NULL);
	pthread_detach(pt_id);	//线程分离	自动回收资源

	while(1){
		//读取数据
		memset(abuf,0x00,sizeof(abuf));
		n = recvfrom(cfd,abuf,sizeof(abuf),0,NULL,NULL);
		printf("n=[%d],buf=[%s]\n",n,abuf);
	}
	//关闭套接字
	close(cfd);

	return 0;
}


void *Send_data(void *arg)
{
	char buf[1400];
	int n,i=0,j;
	struct timeval    tv; 
	struct timezone   tz;
	struct tm         *p;

	while (1)
	{
		sprintf(buf,"cnt=%d  ",i++);
		n = strlen(buf);
		memset(buf+n-1,' ',1450);
		n+=1450+1;
		sendto(cfd,buf,n,0,(struct sockaddr*)&serv,sizeof(serv));
		if(ms!=0)
		usleep(ms*1000);
	}
	
}
